package com.qigao.erp.web.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.qigao.erp.api.LoginInfoService;
import com.qigao.erp.commons.UserService;
import com.qigao.erp.commons.dto.UserCondDto;
import com.qigao.erp.commons.dto.UserResultDto;
import com.qigao.erp.commons.dto.UserUpdateDto;
import com.qigao.erp.commons.enums.Result;
import com.qigao.erp.commons.enums.ResultCode;
import com.qigao.erp.commons.po.UserInfo;
import com.qigao.erp.commons.po.UserPermitResult;
import com.qigao.erp.commons.utils.DateUtil;
import com.qigao.erp.commons.utils.excel.ExcelHeaderInfo;
import com.qigao.erp.commons.utils.excel.ExcelUtils;
import com.qigao.erp.web.utils.RequestUtils;
import com.qigao.erp.web.utils.ValidatorUtil;
import com.qigao.erp.web.vo.api.UserCondVo;
import com.qigao.erp.web.vo.api.UserUpdateVo;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author luiz
 * @Title: AbstractUserController
 * @ProjectName iot
 * @Description: TODO
 * @date 2019-04-17 17:12
 */
@Component
public abstract class AbstractUserController extends AbstractExcelController {
    private static final Logger logger = LoggerFactory.getLogger(AbstractUserController.class);
    @Resource
    private UserService userService;
    @Resource
    private LoginInfoService loginInfoService;
    /**
     * 用户分页条件查询
     */
    @PostMapping("/listPage")
    @ApiOperation(value = "用户分页条件查询", notes = "用户分页条件查询")
    public Result findPage(@RequestBody UserCondVo userCondVo) {
        try {
            UserCondDto userCondDto = buildParam(userCondVo);
            Page<UserResultDto> userPage = userService.findUserPage(userCondDto);
            PageInfo pageInfo = new PageInfo(userPage);
            return Result.newSuccess(pageInfo);
        } catch (Exception e) {
            logger.error("用户分页条件查询失败:{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @PostMapping("/listAll")
    @ApiOperation(value = "获取全部用户信息", notes = "获取全部用户信息")
    public Result listAll() {
        try {
            List<UserResultDto> userResultDtos = userService.findAll();
            return Result.newSuccess(userResultDtos);
        } catch (Exception e) {
            logger.error("获取全部用户信息查询失败:{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    private UserCondDto buildParam(UserCondVo userCondVo) {
        UserCondDto userCondDto = new UserCondDto();
        BeanUtils.copyProperties(userCondVo, userCondDto);
        return userCondDto;
    }


    /**
     * 按照用户编号查询用户
     */
    @ApiOperation(value = "按照用户编号查询用户", notes = "按照用户编号查询用户")
    @GetMapping("/findByUserNo/{userNo}")
    public Result findByUserNo(@PathVariable("userNo") String userNo) {
        try {
            return userService.findByUniqIndex(userNo);
        } catch (Exception e) {
            logger.error("按照用户编号查询用户:{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    /**
     * 修改当前用户信息
     * @param userUpdateVo
     * @return
     */
    @ResponseBody
    @PostMapping("/updateUser")
    @ApiOperation(value = "修改当前用户信息", notes = "修改当前用户信息")
    public Result updateUser(@RequestBody UserUpdateVo userUpdateVo, HttpServletRequest request) {
        try {
            //校验用户实体字段，
            ValidatorUtil.validateEntity(userUpdateVo);
            UserUpdateDto userUpdateDto = new UserUpdateDto();
            BeanUtils.copyProperties(userUpdateVo, userUpdateDto);
            userUpdateDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            Result registerResult = userService.updateUser(userUpdateDto);
            return registerResult;
        } catch (Exception e) {
            logger.error("用户修改资料异常!{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    /**
     * 按照主键ID修改用户信息
     * @param userUpdateVo
     * @return
     */
    @ResponseBody
    @PostMapping("/update")
    @ApiOperation(value = "按照主键ID修改用户信息", notes = "按照主键ID修改用户信息")
    public Result update(@RequestBody UserUpdateVo userUpdateVo) {
        try {
            //校验用户实体字段，
            ValidatorUtil.validateEntity(userUpdateVo);
            UserUpdateDto userUpdateDto = new UserUpdateDto();
            BeanUtils.copyProperties(userUpdateVo, userUpdateDto);
            userUpdateDto.setLoginPass(null);
            //默认等于手机号
            userUpdateDto.setUserNo(userUpdateVo.getPhoneNum());
            userUpdateDto.setTel(userUpdateVo.getPhoneNum());
            if(!StringUtils.isEmpty(userUpdateVo.getEntryDate())){
                userUpdateDto.setEntryDate(DateUtil.formatDate(userUpdateVo.getEntryDate(),"yyyy-MM-dd"));
            }
            if(!StringUtils.isEmpty(userUpdateVo.getFormalDate())){
                userUpdateDto.setFormalDate(DateUtil.formatDate(userUpdateVo.getFormalDate(),"yyyy-MM-dd"));
            }
            Result registerResult = userService.update(userUpdateDto);
            return registerResult;
        } catch (Exception e) {
            logger.error("用户修改资料异常!{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "按照id删除用户", notes = "按照id删除用户")
    public Result<String> del(@PathVariable("id") String id) {
        try {
            return userService.deleteById(Integer.valueOf(id));
        } catch (Exception e) {
            logger.error("删除用户异常!{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    /**
     * getCurrentUser
     *
     * @param request
     * @return
     */
    @GetMapping("/getCurrentUser")
    @ResponseBody
    @ApiOperation(value = "获取当前用户信息", notes = "获取当前用户信息")
    public Result<UserInfo> getCurrentUser(HttpServletRequest request) {
        UserInfo userInfo = RequestUtils.getCurrentUser(request);
        //logger.info("获取当前用户信息:{}",userInfo);
        if (userInfo == null) {
            return Result.newError(ResultCode.USER_NO_LOGGED_IN.getCode(), "当前账户未登录");
        }
        return Result.newSuccess(userInfo);
    }

    /**
     * getCurrentUser
     *
     * @param request
     * @return
     */
    @GetMapping("/getCurrentUserPermit")
    @ResponseBody
    @ApiOperation(value = "获取当前用户权限", notes = "获取当前用户权限")
    public Result<List<UserPermitResult>> getCurrentUserPermit(HttpServletRequest request) {
        UserInfo userInfo = RequestUtils.getCurrentUser(request);
        if (userInfo == null) {
            return Result.newError(ResultCode.USER_NO_LOGGED_IN.getCode(), "当前账户未登录");
        }
        List<UserPermitResult> userPermitResults=loginInfoService.getCurrentUserPermit(userInfo.getUserNo());
        return Result.newSuccess(userPermitResults);
    }


    @GetMapping("/export")
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    public void export( HttpServletResponse response) {
        // 待导出数据
        List<UserResultDto> userResultDtos = userService.findAll();
        ExcelUtils excelUtils = new ExcelUtils(userResultDtos, getHeaderInfo(), null);
        sendHttpResponse(response, "用户数据表", excelUtils.getWorkbook());
    }

    // 获取表头信息
    private List<ExcelHeaderInfo> getHeaderInfo() {
        return Arrays.asList(
                new ExcelHeaderInfo(0, 0, 0, 0, "手机号"),
                new ExcelHeaderInfo(0, 0, 1, 1, "姓名"),
                new ExcelHeaderInfo(0, 0, 2, 2, "用户类型"),
                new ExcelHeaderInfo(0, 0, 3, 3, "用户级别"),
                new ExcelHeaderInfo(0, 0, 4, 4, "是否转正"),
                new ExcelHeaderInfo(0, 0, 5, 5, "推荐人"),
                new ExcelHeaderInfo(0, 0, 6, 6, "推荐人手机号"),
                new ExcelHeaderInfo(0, 0, 7, 7, "所属公司")
        );
    }

}
